import os
import re
import sys
from pathlib import Path

def fix_login_handler(file_path):
    """专门修复LoginHandler.java文件"""
    print(f"Processing file: {file_path}")
    
    # 尝试多种编码读取文件
    encodings = ['utf-8', 'gbk', 'gb2312', 'latin1', 'cp1252']
    content = None
    encoding_used = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            encoding_used = encoding
            print(f"  Successfully read with encoding: {encoding}")
            break
        except UnicodeDecodeError:
            continue
    
    if content is None:
        print(f"  Could not read file with any encoding")
        return False
    
    # 分割为行
    lines = content.split('\n')
    
    # 特别处理第8863行（索引8862）
    line_index = 8862
    if line_index < len(lines):
        original_line = lines[line_index]
        print(f"  Original line 8863: {repr(original_line)}")
        
        # 检查是否有未配对的引号或括号
        fixed_line = original_line
        
        # 检查引号
        if original_line.count('"') % 2 == 1:
            fixed_line = fixed_line + '"'
            print(f"  Added closing quote to line 8863")
        
        # 检查括号
        if original_line.count('(') > original_line.count(')'):
            needed_parens = original_line.count('(') - original_line.count(')')
            fixed_line = fixed_line + ')' * needed_parens
            print(f"  Added {needed_parens} closing parentheses to line 8863")
        
        # 替换原行
        if fixed_line != original_line:
            lines[line_index] = fixed_line
            print(f"  Fixed line 8863: {repr(fixed_line)}")
        
    # 检查并修复文件中的其他问题
    for i, line in enumerate(lines):
        # 处理包含非UTF-8字符的行
        try:
            line.encode('utf-8')
        except UnicodeEncodeError:
            print(f"    Line {i+1}: Contains non-UTF-8 characters, fixing...")
            # 移除非UTF-8字符或替换为空格
            clean_line = ''.join(c if ord(c) < 128 else ' ' for c in line)
            lines[i] = clean_line
    
    # 写回文件
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
        print(f"  Successfully fixed file")
        return True
    except Exception as e:
        print(f"  Error writing file: {e}")
        return False

def main():
    # 确定文件路径
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
    else:
        file_path = "gate-server/src/main/java/com/lastwar/gateserver/login/LoginHandler.java"
    
    if not os.path.isabs(file_path):
        script_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(script_dir, file_path)
    
    if os.path.isfile(file_path):
        fix_login_handler(file_path)
    else:
        print(f"File not found: {file_path}")

if __name__ == "__main__":
    main()